<?php

include_once 'BasicHelper.php';

/**
 * 功能助手类
 * @author chejiulong
 *
 */
class PublicHelper extends BasicHelper {

    public $_Memcache; // Memcache
    public $_tokenID = NULL; // 短信_Token

    function __construct() {
        //$this->__iniMemcache();
    }

    /**
     * 初始化Memcache
     */
    function __iniMemcache() {
        if ($_SERVER ["HTTP_HOST"] != "localhost" && $_SERVER ["HTTP_HOST"] != "127.0.0.1") {

            $this->_Memcache = new Memcache ();
         //   $this->_Memcache->connect('localhost', 11211) or die("Could not connect");
              $this->_Memcache->connect('192.168.0.176', 11211) or die("Could not connect");
        }
    }
    
     /**
     * 获取网页jssdk，自定义传
     * BY WMQ
     * $appid,每个项目的APPID，$url分享链接，$typearr接口类型（不传默认朋友圈和朋友），$debug默认关闭
     * 项目使用例子$row = $this->_PublicHelper->__getSignPackage (WYETH_ACCESS_TOKEN,"",array(1,14,33,12),"true");
     **/
    function __getSignPackage_two($appid=null,$url=null,$typearr=array(),$debug="false",$jsapiTicket ) {
    	//所有JS接口列表
    	$lists = array(
    			'1' => 'onMenuShareTimeline',
    			'2' => 'onMenuShareAppMessage',
    			'3' => 'onMenuShareQQ',
    			'4' => 'onMenuShareWeibo',
    			'5' => 'startRecord',
    			'6' => 'stopRecord',
    			'7' => 'onVoiceRecordEnd',
    			'8' => 'playVoice',
    			'9' => 'pauseVoice',
    			'10' => 'stopVoice',
    			'11' => 'onVoicePlayEnd',
    			'12' => 'uploadVoice',
    			'13' => 'downloadVoice',
    			'14' => 'chooseImage',
    			'15' => 'previewImage',
    			'16' => 'uploadImage',
    			'17' => 'downloadImage',
    			'18' => 'translateVoice',
    			'19' => 'getNetworkType',
    			'20' => 'openLocation',
    			'21' => 'getLocation',
    			'22' => 'hideOptionMenu',
    			'23' => 'showOptionMenu',
    			'24' => 'hideMenuItems',
    			'25' => 'showMenuItems',
    			'26' => 'hideAllNonBaseMenuItem',
    			'27' => 'showAllNonBaseMenuItem',
    			'28' => 'closeWindow',
    			'29' => 'scanQRCode',
    			'30' => 'chooseWXPay',
    			'31' => 'openProductSpecificView',
    			'32' => 'addCard',
    			'33' => 'chooseCard',
    			'34' => 'openCard'
    	);
    	$jsApiList = "[";
    	if(!empty($typearr)){
    		foreach ($lists as $key =>$val){
    			if(in_array($key,$typearr)){
    				$i++;
    				if($i==count($typearr)){
    					$jsApiList .= "'".$val."'";
    				}else{
    					$jsApiList .= "'".$val."',";
    				}
    			}
    		}
    	}else{
    		$jsApiList .= "'onMenuShareTimeline','onMenuShareAppMessage'";
    	}
    	$jsApiList .= "]";
    	//$jsapiTicket = $this->__getWyethAccessToken($appid,1);
    	if(empty($url)){
    		$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
    	}
	    $timestamp = time();
	    $nonceStr = $this->createNonceStr();
	
	    // 这里参数的顺序要按照 key 值 ASCII 码升序排序
	    $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
	    $signature = sha1($string);
	    $signPackage = "wx.config({
	    			debug:$debug,
		            appId:'".$appid."',
		            timestamp:$timestamp,
					nonceStr:'".$nonceStr."',
					signature:'".$signature."',
					jsApiList:$jsApiList
	        	});";
        
	    return $signPackage; 
  }
/**
   * 获取网页jssdk
   * BY WMQ
   * $appid,每个项目的APPID，$url分享链接，$typearr接口类型（不传默认朋友圈和朋友），$debug默认关闭
   * 项目使用例子$row = $this->_PublicHelper->__getSignPackage (WYETH_ACCESS_TOKEN,"",array(1,14,33,12),"true");
   **/
  function __getSignPackageShuzu($appid=null,$url=null,$typearr=array(),$debug="false",$jsapiTicket) 
          {
  	//所有JS接口列表
  	$lists = array(
  			'1' => 'onMenuShareTimeline',
  			'2' => 'onMenuShareAppMessage',
  			'3' => 'onMenuShareQQ',
  			'4' => 'onMenuShareWeibo',
  			'5' => 'startRecord',
  			'6' => 'stopRecord',
  			'7' => 'onVoiceRecordEnd',
  			'8' => 'playVoice',
  			'9' => 'pauseVoice',
  			'10' => 'stopVoice',
  			'11' => 'onVoicePlayEnd',
  			'12' => 'uploadVoice',
  			'13' => 'downloadVoice',
  			'14' => 'chooseImage',
  			'15' => 'previewImage',
  			'16' => 'uploadImage',
  			'17' => 'downloadImage',
  			'18' => 'translateVoice',
  			'19' => 'getNetworkType',
  			'20' => 'openLocation',
  			'21' => 'getLocation',
  			'22' => 'hideOptionMenu',
  			'23' => 'showOptionMenu',
  			'24' => 'hideMenuItems',
  			'25' => 'showMenuItems',
  			'26' => 'hideAllNonBaseMenuItem',
  			'27' => 'showAllNonBaseMenuItem',
  			'28' => 'closeWindow',
  			'29' => 'scanQRCode',
  			'30' => 'chooseWXPay',
  			'31' => 'openProductSpecificView',
  			'32' => 'addCard',
  			'33' => 'chooseCard',
  			'34' => 'openCard'
  					);
  					$jsApiList = "[";
  					if(!empty($typearr)){
  						$i = 0;
  						foreach ($lists as $key =>$val){
  							if(in_array($key,$typearr)){
  								$i++;
  								if($i==count($typearr)){
  									$jsApiList .= "'".$val."'";
  								}else{
  									$jsApiList .= "'".$val."',";
  								}
  							}
  						}
  					}else{
  						$jsApiList .= "'onMenuShareTimeline','onMenuShareAppMessage'";
  					}
  					$jsApiList .= "]";
//  					$jsapiTicket = $this->__getWyethAccessToken($appid,1);
  					if(empty($url)){
  						$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
  					}
  	    $timestamp = time();
  	    $nonceStr = $this->createNonceStr();
  
  	    // 这里参数的顺序要按照 key 值 ASCII 码升序排序
  	    $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
  	    $signature = sha1($string);
  	    
  	    $signPackage = array();
  	    $signPackage['debug'] = $debug;
  	    $signPackage['appId'] = $appid;
  	    $signPackage['timestamp'] = $timestamp;
  	    $signPackage['nonceStr'] = $nonceStr;
  	    $signPackage['signature'] = $signature;
  	    $signPackage['jsApiList'] = $jsApiList;
		$signPackage['jsapiTicket'] = $jsapiTicket;
		$signPackage['url'] = $url;
		return $signPackage;
  }
    /**
     * 清除HTML标签
     *
     * @author donny
     */
    function __delhtml($str) {
        $str = str_replace(array(
            '"',
            "'"
                ), array(
            "",
            ""
                ), $str);
        $st = - 1; // 开始
        $et = - 1; // 结束
        $stmp = array();
        $stmp [] = "&nbsp;";
        $len = strlen($str);
        for ($i = 0; $i < $len; $i++) {
            $ss = substr($str, $i, 1);
            if (ord($ss) == 60) { // ord("<")==60
                $st = $i;
            }
            if (ord($ss) == 62) { // ord(">")==62
                $et = $i;
                if ($st != - 1) {
                    $stmp [] = substr($str, $st, $et - $st + 1);
                }
            }
        }
        $str = str_replace($stmp, "", $str);
        return $str;
    }

    /**
     * 发送短信
     *
     * @param unknown $mobile        	
     * @param unknown $content        	
     * @param string $tokenID        	
     * @return boolean $TokenID
     *         7103040130983487 纪梵希
     *         7100203030727691 惠氏
     *         $cu = curl_init();
     *         curl_setopt($cu, CURLOPT_URL, $url);
     *         curl_setopt($cu, CURLOPT_RETURNTRANSFER, 1);
     *         $ret = curl_exec($cu);
     *         curl_close($cu);
     *         $ret返回如下：
     *         <?xml version="1.0" encoding="utf-8"?>
     *         <string xmlns="http://mms.wemediacn.com/">OK:[201405263018986871030401]</string>
     *         如果返回OK+msgid代表发送成功，如果返回不是OK代表发送失败
     */
    function __sendSMS($mobile, $content, $tokenID = null) {
        if ($tokenID == null && $this->_tokenID != null) {
            $tokenID = $this->_tokenID;
        }
        $url = 'http://www.wemediacn.net/webservice/smsservice.asmx/SendSMS?mobile=' . $mobile . '&FormatID=8&Content=' . urlencode($content) . '&ScheduleDate=2010-1-1&TokenID=' . $tokenID;
        if (strpos(strtolower($this->__https_request($url)), 'ok') !== FALSE) {
            return TRUE;
        } else {
            return FALSE;
        }
    }

    /**
     *
     * @param unknown $arr        	
     */
    function __pr($arr) {
        echo "<pre>";
        print_r($arr);
        echo "</pre>";
    }
    
    /**
     * 
     * 需要传入的项目的APPID
 * 
 * 需要传入当前redis链接的数据库id
     * BY lianghui 170328
     **/
    function __getMpsAccessToken($appid)
    {
    
        $this->__MpsiniRedis();
       
        $tokeninfo= json_decode($this->_MpsRedis->hGet("mp_authorizer_access_token",$appid),true);
  
         $tokeninfo['access_token']=$tokeninfo['authorizer_access_token'];
         return $tokeninfo;
       
    }
    /**
	 * 初始化redis哪里用哪里调
	 *
	 */
	public function __MpsiniRedis(){
		$this->_MpsRedis = new Redis ();
		 $this->_MpsRedis->connect('10.161.233.107', 6379) or die("redis Could not connect");
                	$code = 'AQaPLWyGaFs1fI9YzT9uKwHgXdymcybC';
		$this->_MpsRedis->auth($code);
                 $this->_MpsRedis->select(15);//正式redis
	}

    /**
     * 图片是否存在
     *
     * @param type $url        	
     * @return boolean
     */
    function __img_exits($url) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_NOBODY, 1); // 不下载
        curl_setopt($ch, CURLOPT_FAILONERROR, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        if (curl_exec($ch) !== false)
            return true;
        else
            return false;
    }

    // 上传图片到百度云网盘
    // 例$band="givenchy",$path ="images/gold"
    function __upload_img_pan($band, $path) {
        ignore_user_abort(); //关掉浏览器，PHP脚本也可以继续执行.
        set_time_limit(0); // 通过set_time_limit(0)可以让程序无限制的执行下去
        $dir = dirname(dirname(__FILE__)) . '/' . $band . '/webroot/' . $path; // 讲网络路径转换成文件路径

        $files1 = scandir($dir); // 扫描文件，返回一个数组
        $files1Arr = array_slice($files1, 2); // 去除头两个
        
        foreach ($files1Arr as $val) {


            $ext = strrchr($val, '.'); // 判断是图片还是文件夹，如果是文件返回false
            if (!$ext) {
                $files2 = scandir($dir . '/' . $val); // 扫描文件，返回一个数组
                $files1Arr2 = array_slice($files2, 2); // 去除头两个
                foreach ($files1Arr2 as $childval) {

                    $is_exist = $this->__img_exits("http://bcs.duapp.com/wemediacn-sh2/" . $band . '/' . $path . '/' . $val . '/' . $childval);
                    $loacal_im_text = sha1_file($dir . '/' . $val . '/' . $childval);   //本地图片内容
                    $online_im_text = sha1_file("http://bcs.duapp.com/wemediacn-sh2/" . $band . '/' . $path . '/' . $val . '/' . $childval);   //网盘图片内容
                    // 上传
                    if (!$is_exist || $loacal_im_text != $online_im_text) {
                        $childinfo = $this->__https_request("http://wxapp.wemediacn.com/Weyun/putfile.ashx?token=163d1c8bad16428ab97e635af25e3b61&filename=" . $band . '/' . $path . '/' . $val . '/' . $childval . "&url=http://" . $band . '.weshwx.cn/' . $path . "/" . $val . '/' . $childval);
                        $childreturn_info = (array) json_decode($childinfo);

                        if ($childreturn_info ['errcode'] != 0) {
                            echo $childreturn_info ['msg'];
                            echo "</br>";
                        }
                    }
                }
            } else {

                $is_exist = $this->__img_exits("http://bcs.duapp.com/wemediacn-sh2/" . $band . '/' . $path . '/' . $val);
                // 上传
                $loacal_im_text = sha1_file($dir . '/' . $val);   //本地图片内容
                $online_im_text = sha1_file("http://bcs.duapp.com/wemediacn-sh2/" . $band . '/' . $path . '/' . $val);   //网盘图片内容
                // 上传
                if (!$is_exist || $loacal_im_text != $online_im_text) {
                     
                    $info = $this->__https_request("http://wxapp.wemediacn.com/Weyun/putfile.ashx?token=163d1c8bad16428ab97e635af25e3b61&filename=" . $band . '/' . $path . '/' . $val . "&url=http://" . $band . '.weshwx.cn/' . $path . '/' . $val);

                    $return_info = json_decode($info, true);

                    if ($return_info ['errcode'] != 0) {
                        echo $return_info ['msg'];
                        echo "</br>";
                    }
                }
            }
        }
    }

    // 定义图片路径变量
    function __imgpath($type, $band, $path) {
        if ($type == 1) {
            if ($_SERVER ["HTTP_HOST"] == "localhost" ) {
                   $imgpath =  '../'.$path;
            }else{
                   $imgpath = "http://" . $_SERVER ['HTTP_HOST'] . '/' . $path;
            }
         
        } else {
            $imgpath = 'http://bcs.duapp.com/wemediacn-sh2/' . $band . '/' . $path;
        }
        return $imgpath;
    }
    
    
    
    
    /**
     * 所有项目获取AccessToken
     * 需要传入的项目的APPID
     * BY WMQ
     **/
    function __getWyethAccessToken($appid,$type=null)
    {
    	$Accountids = array(
    			// 惠氏
    			'wx7fd6725300a50716' => array(
    					'aid' => '3DB2ACBD-502D-4E5C-BE68-45B6B903FE0E',
    			),
    			//用的相宜本草来测试
    			'wxdfc5e5a9feea1c4b' => array(
    					'aid' => '879942D8-3C4B-4E74-8DD0-D64D41197513',
    			),
                        //珀莱雅
                        'wx3878095d9a38bd21' => array(
    					'aid' => '32C016FF-3100-45C1-A318-685BDEDDD160',
    			),
    			//欧莱雅acd
    			'wx1aeccbec6c8b929b' => array(
    					'aid' => 'B963F9CC-4539-4DEE-996D-E0031FDB0E95',
    			),
    			//兰芝
    			'wx61c03ce66f14b0c3' => array(
    					'aid' => '13BCC940-11D6-4A12-B095-05855A3CB0F2',
    			),
    			//微杂志
    			'wx39897bf85ab8c435' => array(
    					'aid' => '6B8C0376-A8B2-4D22-B555-40445319EBD8',
    			)
    	);
    	if(!empty($Accountids[$appid]))
    	{
    		$time = time();
    		$tmpArr = array($Accountids[$appid]['aid'], $time, 'v2', 'we2014');
    		sort($tmpArr, SORT_STRING);
    		$tmpStr = implode( $tmpArr );
    		$requestUri = 'http://wxapp.wemediacn.com/accesstoken/get/?accountid=' . $Accountids[$appid]['aid'] . '&time=' . $time . '&sign=' . md5($tmpStr);
    			
    		$res = $this->sendAccessToken($requestUri);
    		if($type==1){//获取的是jsapiTicket
    			$js_token = $res['ticket'];
    			return $js_token;
    		}else{
    			$access_token = $res['msg'];
    			return $access_token;
    		}

        }elseif($appid=='wx1fd3bfd59423adbd'){
            	$this->kanjia_access_token = 'kanjia_access_token';
		$access_token = $this->_Memcache->get ( $this->kanjia_access_token );
		if (! empty ( $access_token )) {
//                    var_dump($access_token);die;	
                    return $access_token['jsapiTicket'];
		} else {
			$infoArr = array ();
			$access_tokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx1fd3bfd59423adbd&secret=aa1979ac9f7a09acd7b4138edf9f9ae2";
			$wechat_token = $this->__https_request ( $access_tokenUrl );
			$wechat_token = json_decode ( $wechat_token, true );
			$infoArr ['access_token'] = $access_token = $wechat_token ['access_token'];
			$jsapiTicket = $this->__https_request ( "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" . $wechat_token ['access_token'] . "&type=jsapi" );
			$jsapiTicket = json_decode ( $jsapiTicket, true );
//                          var_dump($jsapiTicket);die;
			$infoArr ['jsapiTicket'] = $jsapiTicket ['ticket'];
			$this->_Memcache->set ( $this->kanjia_access_token, $infoArr, false, 6000 );
			return $infoArr['jsapiTicket'];
		}
        }
    }
    function sendAccessToken($requestUril)
    {
    
    	$res = $this->__https_request($requestUril);
    
    	if(empty($res))
    	{
    		$res = '{}';
    	}
    	 
    	$res = json_decode($res , TRUE);
    
    	return $res;
    }
    /**
     * 给用户推送消息方法
     * 第一个参数是用户的OPENID第二个参数是发送给用户的内容第三个是APPid
     **/
    function __sendQuestionnaire($openId,$content,$appid){
    	$str = $this->__formatTextJsonQuestionnaire($openId,$content);
    	$res = $this->__sendMessageQuestionnaire($str,$appid);
    	return $res;
    }
    function __formatTextJsonQuestionnaire($toUserName, $content)
    {
    	return '{
            "touser":"' . $toUserName . '",
            "msgtype":"text",
            "text":{
                "content":"' . str_replace('"', '\"', $content)  . '"
            }
        }';
    }
    function __sendMessageQuestionnaire($postStr,$appid)
    {
    	$url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=';
//     	print_r($appid);
    	//获取access_token
    	$access_token = $this->__getWyethAccessToken($appid);
    	$requestUri = $url.$access_token;
//     	print_r($access_token);
//     	 print_r($requestUri);die;
    	$res = $this->sendMessage($requestUri,$postStr);
    	if(!empty($res["errcode"]))
    	{
    		if($res["errcode"] == 40001)
    		{
    			$requestUri = $url.$access_token;
    
    			$res = $this->sendMessage($requestUri,$postStr);
    		}
    	}
    
    	return $res;
    }
    
    function sendMessage($requestUri, $params=null)
    {
    	$res = $this->__http_post_request($requestUri,$params);
    
    	if(empty($res))
    	{
    		$res = '{}';
    	}
    
    	$res = json_decode($res , TRUE);
    
    	return $res;
    }
    
    
    /**
     * 获取网页jssdk
     * BY WMQ
     * $appid,每个项目的APPID，$url分享链接，$typearr接口类型（不传默认朋友圈和朋友），$debug默认关闭
     * 项目使用例子$row = $this->_PublicHelper->__getSignPackage (WYETH_ACCESS_TOKEN,"",array(1,14,33,12),"true");
     **/
    function __getSignPackage($appid=null,$url=null,$typearr=array(),$debug="false") {
    	//所有JS接口列表
    	$lists = array(
    			'1' => 'onMenuShareTimeline',
    			'2' => 'onMenuShareAppMessage',
    			'3' => 'onMenuShareQQ',
    			'4' => 'onMenuShareWeibo',
    			'5' => 'startRecord',
    			'6' => 'stopRecord',
    			'7' => 'onVoiceRecordEnd',
    			'8' => 'playVoice',
    			'9' => 'pauseVoice',
    			'10' => 'stopVoice',
    			'11' => 'onVoicePlayEnd',
    			'12' => 'uploadVoice',
    			'13' => 'downloadVoice',
    			'14' => 'chooseImage',
    			'15' => 'previewImage',
    			'16' => 'uploadImage',
    			'17' => 'downloadImage',
    			'18' => 'translateVoice',
    			'19' => 'getNetworkType',
    			'20' => 'openLocation',
    			'21' => 'getLocation',
    			'22' => 'hideOptionMenu',
    			'23' => 'showOptionMenu',
    			'24' => 'hideMenuItems',
    			'25' => 'showMenuItems',
    			'26' => 'hideAllNonBaseMenuItem',
    			'27' => 'showAllNonBaseMenuItem',
    			'28' => 'closeWindow',
    			'29' => 'scanQRCode',
    			'30' => 'chooseWXPay',
    			'31' => 'openProductSpecificView',
    			'32' => 'addCard',
    			'33' => 'chooseCard',
    			'34' => 'openCard'
    	);
    	$jsApiList = "[";
    	if(!empty($typearr)){
    		foreach ($lists as $key =>$val){
    			if(in_array($key,$typearr)){
    				$i++;
    				if($i==count($typearr)){
    					$jsApiList .= "'".$val."'";
    				}else{
    					$jsApiList .= "'".$val."',";
    				}
    			}
    		}
    	}else{
    		$jsApiList .= "'onMenuShareTimeline','onMenuShareAppMessage'";
    	}
    	$jsApiList .= "]";
    	$jsapiTicket = $this->__getWyethAccessToken($appid,1);
         
    	if(empty($url)){
    		$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
    	}
	    $timestamp = time();
	    $nonceStr = $this->createNonceStr();
	
	    // 这里参数的顺序要按照 key 值 ASCII 码升序排序
	    $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
	    $signature = sha1($string);
	    $signPackage = "wx.config({
	    			debug:$debug,
		            appId:'".$appid."',
		            timestamp:$timestamp,
					nonceStr:'".$nonceStr."',
					signature:'".$signature."',
					jsApiList:$jsApiList
	        	});";
	    return $signPackage; 
  }
  private function createNonceStr($length = 16) {
  	$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  	$str = "";
  	for ($i = 0; $i < $length; $i++) {
  		$str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
  	}
  	return $str;
  }
}
